<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Email;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;
use think\Request;
use fast\Http;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third','search'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        // 
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        if(!Session::get('userName')){
            $this->auth->logout();
        }
        $this->view->assign('userName', Session::get('userName'));
        return $this->view->fetch();
    }

    public function mylist(){
        // var_dump(session('token')); 
        $list = Db::table('fa_warranty')->where(['userName'=>Session::get('userName')])->select(); 
        $this->view->assign('sum',count($list));
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }
    public function mylisthas(){
        //平安3年
        $threeYears = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'11077003900613414447'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('threeYears',$threeYears);
        //人保旧3年
        $threeOneYears = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH201942010000000095'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('threeOneYears',$threeOneYears);

        //人保新1年
        $rbOneYears = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000010'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('rbOneYears',$rbOneYears);

        //人保新3年
        $rbthreeYears = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000011'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('rbthreeYears',$rbthreeYears);

        //平安1年
        $oneYears = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'11077003900529071292'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('oneYears',$oneYears);

         //平安3年10w
        $pa3Years10w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(10w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('pa3Years10w',$pa3Years10w);

        //平安3年15w
        $pa3Years15w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(15w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('pa3Years15w',$pa3Years15w);


          //平安3年15w
        $pa3YearsYX15w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(YX15w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('pa3YearsYX15w',$pa3YearsYX15w); 
        //平安3年20w
        $pa3Years20w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(20w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('pa3Years20w',$pa3Years20w);

        //平安3年30w
        $pa3Years30w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(30w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('pa3Years30w',$pa3Years30w);

        //平安3年30w
        $pa3Years40w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(40w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('pa3Years40w',$pa3Years40w);


         //途强3年50w
        $tq3Years50w = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH201942010000000077(TQ50w)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('tq3Years50w',$tq3Years50w);








        //新20万3年
        $new20w3y = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(NEW 20W)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('new20w3y',$new20w3y);

        //新40万3年
        $new40w3y = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(NEW 40W)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('new40w3y',$new40w3y);

        //新20万1年
        $new20w1y = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000074(20W)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('new20w1y',$new20w1y);

        //途强3年50w
        $new50w1y = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000074(50W)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('new50w1y',$new50w1y);





        //一年意外
        $new1yw = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000074(10W)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('new1yw',$new1yw);
        //三年意外
        $new3yw = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>'PZAH202042010000000051(NEW 10W)'])->where('nullify','=','0')->where('pay_status','>',0)->count();  
        $this->view->assign('new3yw',$new3yw);


 
        return $this->view->fetch();
    }
    public function editCarNo(){
        try { 
            $dd = $this->request->post(); 
            $res = Db::table('fa_order')->where(['id'=>$dd['id']])->update(['car_no'=>$dd['car_no'],'dj_time'=>strtotime($dd['dj_time'])]);
            if($res>0 || $res===0){ 

                $result = Db::table('fa_order')->where('id', $dd['id'])->find(); 
                if($result['insurance_company'] == 'PICC'){
                     $this->sendEmail($result['id'],$result['big_number'],$result['small_number'],$result['real_name'],'保单修改',$result['email']);
                }

                echo json_encode(['code'=>1,'msg'=>'编辑成功']);
                exit;
            }else{
                echo json_encode(['code'=>0,'msg'=>'编辑失败']);
                exit;
            }
        } catch (Exception $e) { 
            echo json_encode(['code'=>0,'msg'=>$e->getMessage()]);
            exit;
        }
    }
       //发送邮箱
    private function sendEmail($id,$big_number,$small_number,$name,$type,$email_address){
        \think\Config::set('site', array_merge(\think\Config::get('site'), [])); 
        $email = new Email;
        $html = file_get_contents("http://wx.350gps.cn/index/order/index.html?id={$id}");
        $result = $email
            ->to($email_address)
            ->subject("大保单{$big_number}子保单{$small_number}客户名字{$name}【{$type}】")
            ->message($html)
            ->send(); 
    }
    public function listover(){
        $query = Request::instance()->param();  
        // $safe_years = $this->request->get('safe_years');
        $type = $this->request->get('type');
        $list = Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>$type])->where('pay_status','>',0)->where('nullify','=','0')->order('id desc')->paginate(10,false,['type'=>'bootstrap','var_page' => 'page','query'=>$query]);  
        $this->view->assign('sum',Db::table('fa_order')->where(['userName'=>Session::get('userName'),'big_number'=>$type])->where('pay_status','>',0)->where('nullify','=','0')->count()); 
        // 获取分页显示
        $page = $list->render(); 

        // foreach ($list as $key => $value) { 
        //     $list[$key]['differ'] = intval((time()-$value['create_time'])/3600);
        // }

        $this->view->assign('list',$list);
        if(!isset($query['page'])){
            $query['page'] = 1;
        }
        $this->assign('page', $page);
        $this->assign('query',$query);
        return $this->view->fetch();
    }
    public function mylistnullify(){
        $query = Request::instance()->param();   
        $list = Db::table('fa_order')->where(['userName'=>Session::get('userName')])->where('pay_status','>',0)->where('nullify','=','1')->order('id desc')->paginate(10,false,['type'=>'bootstrap','var_page' => 'page','query'=>$query]);  
        $this->view->assign('sum',Db::table('fa_order')->where(['userName'=>Session::get('userName')])->where('pay_status','>',0)->where('nullify','=','1')->count()); 
        // 获取分页显示
        $page = $list->render(); 
        $this->view->assign('list',$list);
        if(!isset($query['page'])){
            $query['page'] = 1;
        }
        $this->assign('page', $page);
        $this->assign('query',$query);
        return $this->view->fetch();
    }

    public function getTreeList(){  
        $url = "api/ucorgan/getorgantree"; 
        $userlist = Http::sendRequest($url,[],'GET',[],true,session('token')); 
        echo json_encode($userlist);
        exit;
    }
    public function  turnout(){
        if(!$this->request->isPost()){  
            // $url = "api/ucorgan/getorgantree"; 
            // $userlist = Http::sendRequest($url,[],'GET',[],true,session('token')); 
            // $userjson  = json_encode($userlist['retobj']);

            // $this->view->assign('userjson',$userjson); 

            // // var_dump($id);
        
            // $url = "api/ucorgan/getorgantree"; 
            // $result = Http::sendRequest($url,[],'GET',[],true,Session::get('token'));  

            // $ctype = $this->request->get('ctype');
            // $this->view->assign('ctype',$ctype); 

            $type = $this->request->get('type'); 
            $info = Db::table('fa_warranty')->where(['type'=>$type,'userName'=>Session::get('userName')])->find(); 
 
            $this->view->assign('info',$info); 
            return $this->view->fetch(); 
        }else{
            $ylid = $this->request->post('ylid');
            $ylnum = $this->request->post('ylnum');
            $yluserName = $this->request->post('yluserName');
            $num = $this->request->post('num');
            $userName = $this->request->param('userName'); 
            $safe_years = $this->request->post('safe_years');
            $insurance_company = $this->request->post('insurance_company');
            $type = $this->request->post('type');

            if($insurance_company == 'PICC'){
                $title = '中国人民财产保险';
            }else{
                $title = '中国平安保险'; 
            }
            //验证用户是否存在
            $this->addOrderLog(['userName'=>$yluserName,'type'=>'转移','remark'=>'转移[ '.$title.$type.' ]保单'.$num.'份给'.$userName]);
            //更新本地数据库操作
            $result = Db::table('fa_warranty')->where(['userName'=>$userName,'safe_years'=>$safe_years,'insurance_company'=>$insurance_company,'type'=>$type])->find();
            if($result){
                Db::table('fa_warranty')->where(['userName'=>$userName,'safe_years'=>$safe_years,'insurance_company'=>$insurance_company,'type'=>$type])->update(['num'=>$result['num']+$num]);
            }else{ 
                Db::table('fa_warranty')->insert(['userName'=>$userName,'safe_years'=>$safe_years,'source'=>$yluserName,'num'=>$num,'insurance_company'=>$insurance_company,'type'=>$type,'createTime'=>time(),'activeTime'=>time()]);
            } 
            Db::table('fa_warranty')->where(['userName'=>$yluserName,'safe_years'=>$safe_years,'type'=>$type])->update(['num'=>$ylnum-$num]);
            $this->success('转入成功', url('user/mylist'));
        }
    }
    public function addOrderLog($data){
        $data['create_time'] = time();
        return Db::table('fa_order_log')->insert($data); 
    }
    public function search(){ 
        if($this->request->isPost()){
            $big_number = $this->request->post('big_number');
            $small_number = $this->request->post('small_number');
            // $real_name = $this->request->post('real_name');
            // $card_no = $this->request->post('card_no');

            $tel = $this->request->post('tel');

            if(!$small_number||!$tel){ 
                $this->error('请输入保单号和用户手机号查询',url('user/search'));
            }  
            $where = ['big_number'=>$big_number,'small_number'=>$small_number,'tel'=>$tel]; 
            $res =  Db::table('fa_order')->where($where)->select(); 

            $this->view->assign('list',$res);

            if(!empty($res)){  
                return $this->view->fetch('searchlist');
            }else{
                $this->error('暂无数据',url('user/search'));
            }

            // var_dump($res);

            // if(!empty($res)){  
            //     $this->redirect('Order/index', ['id' => $res[0]['id']]);
            // }else{
            //     $this->error('暂无数据',url('user/search'));
            // }
        }
        return $this->view->fetch();
    }
    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url', '', 'trim');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'captcha.require'  => 'Captcha can not be empty',
                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'trim');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:1,50',
                'password'  => 'require|length:1,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 5 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout|user\/search)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        Session::set('userName','');
        $this->success(__('Logout successful'), url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

}
